package com.yhsimon.rabbitmq.all;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

/**
 * 代码实现exchange绑定queue
 *
 * 通过debug的方式 在图形化界面查看连接状态
 */
public class Producer {
    public static void main(String[] args) {
        //所有的中间件技术都是基于TCP/IP协议基础上构建新型的协议规范，而RabbitMq遵循的是amqp
        //ip port
        //1. 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.100.128");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("/");

        Connection connection=null;
        Channel channel=null;
        try {
            //2. 创建连接Connection
            connection= connectionFactory.newConnection("生产者");
            //3. 通过连接获取通道Channel
            channel = connection.createChannel();

            /**
             * @Param1 队列的名称
             * @Param2 是否要持久化durable=false false是非持久化  true是持久化  非持久化是否会存盘
             * @Param3 排他性，即是否是独占独占
             * @Param4 是否自动删除，随着最后一个消费消息完毕后是否把队列自动删除
             * @Param1 携带附属参数
             */
            //5.准备消息内容
            String message="Hello World! direct_order message!!!!";

            //6.准备交换机
            String exchangeName="direct_order_exchange";
            //交换机的类型 direct/fanout/topic/headers
            String exchangeType="direct";
            //7.声明交换机
            channel.exchangeDeclare(exchangeName,exchangeType,true);

            //8.声明队列
            channel.queueDeclare("queue5",true,false,false,null);
            channel.queueDeclare("queue6",true,false,false,null);
            channel.queueDeclare("queue7",true,false,false,null);

            //9.绑定队列与交换机的关系
            channel.queueBind("queue5",exchangeName,"order");
            channel.queueBind("queue6",exchangeName,"order");
            channel.queueBind("queue7",exchangeName,"email");



            channel.basicPublish(exchangeName,"order",null,message.getBytes());
            System.out.println("消息发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //7. 关闭通道
            if(channel!=null&&channel.isOpen()){
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //8. 关闭连接
            if(connection!=null&&connection.isOpen()){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
